package com.tumanex.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.Toast;

import com.tumanex.R;
import com.tumanex.adapters.MyPicturesGalleryAdapter;
import com.tumanex.dialog.Dialogs;
import com.tumanex.simplepaint.Painter;

/**
 * 
 * @author artemka
 * 
 */
public class MyPicturesActivity extends BaseActivity implements OnClickListener {

	private static final String sharedPicturesName = "Last shared picture";

	private static final int ID_ITEM_SHARE = 0;
	private static final int ID_ITEM_DELETE = 1;

	public static final String PICTURE_MIME = "image/png";

	private static int choosenPosPicture;

	private Gallery mGallery;

	private MyPicturesGalleryAdapter mAdapter;

	private Handler mHandler;
	private Dialogs downloadActivity;

	private int DOWNLOAD_ACTIVITY_DELEY = 200;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		createHandler();

		startProgActivityDownload();

		onCreateInThread();
	}

	@Override
	protected void initViews() {
		super.initViews();

		mGallery = (Gallery) findViewById(R.id.galleryMyPictures);
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case R.id.dialog_item_gallery:
			return createItemChoiseDialog();

		default:
			return super.onCreateDialog(id);
		}

	}

	private boolean checkEmptyGallery() {

		if (mAdapter.getCount() == 0) {

			setContentView(R.layout.mypicture_is_empty);
			return true;
		}
		return false;
	}

	public Dialog createItemChoiseDialog() {

		AlertDialog.Builder adb = new AlertDialog.Builder(
				MyPicturesActivity.this);

		adb.setTitle(R.string.mypicture_item_tl);
		adb.setItems(R.array.mypicture_item_option, this);

		return adb.create();
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {

		switch (which) {

		case ID_ITEM_SHARE:

			share();
			break;

		case ID_ITEM_DELETE:

			Log.d("item delete", "Choosen position = " + choosenPosPicture);

			mAdapter.deleteSaveImage(choosenPosPicture);
			mAdapter.updataData();
			mAdapter.notifyDataSetChanged();
			checkEmptyGallery();
			break;
		}
	}

	private void share() {

		// String path = Images.Media.insertImage(getContentResolver(),
		// mAdapter.getImageByPos(choosenPosPicture), sharedPicturesName,
		// null);

		// Uri imageUri = Uri.parse(path);

		Uri imageUri = saveLastSharePicture();

		Intent i = new Intent(Intent.ACTION_SEND);
		i.setType(PICTURE_MIME);
		i.putExtra(Intent.EXTRA_STREAM, imageUri);
		startActivity(Intent.createChooser(i,
				getString(R.string.share_image_title)));

	}

	private boolean isStorageAvailable() {
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			Toast.makeText(this, R.string.sd_card_not_writeable,
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, R.string.sd_card_not_available,
					Toast.LENGTH_SHORT).show();
		}

		return false;
	}

	private Uri saveLastSharePicture() {

		if (!isStorageAvailable()) {

			return null;
		}

		String path = Environment.getExternalStorageDirectory()
				.getAbsolutePath()
				+ '/'
				+ getString(R.string.app_name)
				+ '/'
				+ sharedPicturesName + Painter.PICTURE_EXT;

		File file = new File(path);

		try {
			saveBitmapInFile(path);
		} catch (FileNotFoundException e) {
		}

		return Uri.fromFile(file);

	}

	public void saveBitmapInFile(String FileName) throws FileNotFoundException {

		FileOutputStream fos = new FileOutputStream(FileName);
		mAdapter.getImageByPos(choosenPosPicture).compress(CompressFormat.PNG,
				100, fos);

	}

	public void createHandler() {

		mHandler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				super.dispatchMessage(msg);

			}
		};
	}

	public void startProgActivityDownload() {

		mHandler.post(new Runnable() {

			@Override
			public void run() {

				downloadActivity = new Dialogs(MyPicturesActivity.this);
				downloadActivity.showActivityDownload();
			}
		});
	}

	public void onCreateInThread() {

		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {

				mAdapter = new MyPicturesGalleryAdapter(MyPicturesActivity.this);

				if (!checkEmptyGallery()) {

					setContentView(R.layout.activity_mypictures);
					initViews();
					mGallery.setAdapter(mAdapter);

					mGallery.setOnItemClickListener(new OnItemClickListener() {

						@SuppressWarnings("deprecation")
						@Override
						public void onItemClick(AdapterView<?> parent, View v,
								int position, long id) {

							choosenPosPicture = position;
							showDialog(R.id.dialog_item_gallery);
						}
					});
				}

				endProgActivityDownload();
			}
		}, DOWNLOAD_ACTIVITY_DELEY);
	}

	public void endProgActivityDownload() {

		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {

				downloadActivity.dismissActivityDownload();
			}
		}, DOWNLOAD_ACTIVITY_DELEY);

	}

}